package com.alks.yn_zs.service.serviceImpl;

import com.alks.common.aop.AutoPageAop;
import com.alks.common.utils.beanutils.ArrayUtils;
import com.alks.entity.data.page.PageRecord;
import com.alks.yn_zs.data.dto.MtlInDto;
import com.alks.yn_zs.data.dto.StatsDto;
import com.alks.yn_zs.data.request.MtlInRequest;
import com.alks.yn_zs.data.request.StatsRequest;
import com.alks.yn_zs.format.DateFormat;
import com.alks.yn_zs.mapper.MtlShowMapper;
import com.alks.yn_zs.service.IMtlShowService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author MS
 * @since 2024/11/12上午10:10
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class MtlShowServiceImpl implements IMtlShowService {
    private final MtlShowMapper showMapper;


    @Override
    @AutoPageAop(count = false)
    public PageRecord<MtlInDto> mtlInDet(MtlInRequest request) {
        /*获取数据*/
        List<MtlInDto> checkList = showMapper.showMtlInDet(request);
        return new PageRecord<>(checkList);
    }

    @Override
    @AutoPageAop(count = false)
    public PageRecord<MtlInDto> mtlStkDet(MtlInRequest request) {
        /*获取数据*/
        List<MtlInDto> checkList = showMapper.showMtlStkDet(request);
        return new PageRecord<>(checkList);
    }

    @Override
    public List<StatsDto> mtlIoStq(StatsRequest request) {
        /*初始化*/
        DateFormat.start(request);
        /*获取指定时间内出入库数据*/
        List<StatsDto> dtoList = showMapper.mtlIoStatusQuery(request.getStartDate(), request.getEndDate());
        if (ArrayUtils.isEmpyt(dtoList)){
            return List.of();
        }
        String[] typeName = {"I","O"};
        /*对出入库数据分组*/
        Map<String, List<StatsDto>> titleMap = dtoList.stream()
                .collect(Collectors.groupingBy(a -> DateFormat.formatKey(request.getTitleUnit(), a.getDate())+"_"+a.getType()));
        dtoList.clear();
        titleMap.forEach((key, value)->{
            String[] split = key.split("_");
            String title = split[0].replace("-", "");
            String type = split[1];
            StatsDto dto = new StatsDto();
            BigDecimal count = value.stream()
                    .map(StatsDto::getCount)
                    .filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            dto.setDate(value.get(0).getDate());
            dto.setTitle(title);
            dto.setCount(count);
            dto.setType(type);
            dtoList.add(dto);
        });
        DateFormat.fillMissingAndSort(dtoList,request.getTitleUnit(),request.getStartDate(),request.getEndDate(),typeName);
        return dtoList;

    }
}
